<template>
  <div class="case-analysis-dashboard">
    <!-- 智能助手头部信息区域 -->
    <div class="assistant-header">
      <div class="header-content">
        <img class="robot-img" src="@/assets/img/robot.gif" alt="智能助手形象">
        <div class="assistant-info">
          <h2 class="welcome-title">Hi~我是小诺！</h2>
          <p class="welcome-desc">下午好！我是您的案件智能小助手，您可以基于案件咨询您的问题</p>
        </div>
      </div>
      <div class="header-bg"></div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <van-search v-model="searchValue" placeholder="请输入案件名称或关键词" shape="round" clearable background="#f7f8fa"
        @search="handleSearch">
        <template #left-icon>
          <van-icon name="search" size="16" />
        </template>
      </van-search>
    </div>

    <!-- 案件列表区域 -->
    <div class="case-list">
      <div class="section-title">
        <h3>我的案件</h3>
        <div >
          <van-button  style="margin-right: 10px;" type="primary" size="mini" plain @click="toGenerateClaimReport">
            <van-icon name="plus" size="14" />
            生成诉状书
          </van-button>
          <van-button  type="primary" size="mini" plain @click="addNewCase">
            <van-icon name="plus" size="14" />
            新增案件
          </van-button>
        </div>
      </div>

      <CaseCardList v-if="filteredCaseList.length > 0"  :case-list="filteredCaseList" @item-click="viewCaseDetail" @item-delete="deleteCase"
        @evidence-click="showActionSheet" />
        <van-empty
        v-else
        description="暂无案件分析记录，开始您的第一次案件分析问答吧！"
        image-size="120px"
      ></van-empty>
    </div>

    <!-- 新增案件弹窗 -->
    <van-dialog v-model:show="showAddDialog" title="新增案件" show-cancel-button @confirm="confirmAddCase">
      <van-form @submit="confirmAddCase">
        <van-cell-group inset>
          <van-field v-model="newCase.caseName" label="案件名称" placeholder="请输入案件名称"
            :rules="[{ required: true, message: '请填写案件名称' }]" />
          <van-field v-model="newCase.caseProcedure" label="案件程序" placeholder="请选择案件程序" is-link readonly clickable
            :rules="[{ required: true, message: '请选择案件程序' }]" @click="showProcedurePicker = true" />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <!-- 修改案件弹窗 -->
    <van-dialog v-model:show="showEditDialog" title="修改案件" show-cancel-button @confirm="confirmEditCase">
      <van-form @submit="confirmEditCase">
        <van-cell-group inset>
          <van-field v-model="editCase.caseName" label="案件名称" placeholder="请输入案件名称"
            :rules="[{ required: true, message: '请填写案件名称' }]" />
          <van-field v-model="editCase.caseProcedure" label="案件程序" placeholder="请选择案件程序" is-link readonly clickable
            :rules="[{ required: true, message: '请选择案件程序' }]" @click="showEditProcedurePicker = true" />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <!-- 案件程序选择器 -->
    <van-popup v-model:show="showProcedurePicker" round position="bottom">
      <van-picker title="选择案件程序" :columns="procedureColumns" @confirm="onProcedureConfirm"
        @cancel="showProcedurePicker = false" />
    </van-popup>

    <!-- 修改案件程序选择器 -->
    <van-popup v-model:show="showEditProcedurePicker" round position="bottom">
      <van-picker title="选择案件程序" :columns="procedureColumns" @confirm="onEditProcedureConfirm"
        @cancel="showEditProcedurePicker = false" />
    </van-popup>

    <!-- 操作菜单 -->
    <van-action-sheet v-model:show="showAction" :actions="actions" @select="onSelect" class="custom-action-sheet" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showConfirmDialog, showToast } from 'vant';
import CaseCardList from '@/components/CaseCardList.vue';
import { ElMessage, ElLoading } from 'element-plus';
import { getChatHistoriesByUserNo, uploadCaseFile, addCase, updateCase, deleteCaseById } from '@/api/analysis';

interface CaseListItem {
  id: number;
  caseName: string;
  analysisStatus: '已分析' | '未分析' | '分析中';
  evidenceUpload: '已完成' | '未上传';
  caseProcedure: string;
  victoryRate: number;
  createTime: string;
}
const router = useRouter();
// 案件数据
const caseList = ref<CaseListItem[]>([]); // 案件列表

const searchValue = ref(''); // 搜索关键词
const showAddDialog = ref(false); // 新增案件弹窗
const showEditDialog = ref(false); // 修改案件弹窗
const showAction = ref(false); // 操作菜单
const showProcedurePicker = ref(false); // 案件程序选择器
const showEditProcedurePicker = ref(false); // 修改案件程序选择器

/* ============== 案件程序模块 ===================== */
/**
 * 基础的案件功能区域块
 * 1. 案件程序选项（procedureColumns）
 * 2. 新增案件表单（newCase）
 * 3. 修改案件表单（editCase）
 * 4.当前选中的案件
 * 5. 案件程序选择确认（onProcedureConfirm ），修改确认（onEditProcedureConfirm）
 */
// 案件程序选项
const procedureColumns = [
  { text: '一审', value: '一审' },
  { text: '二审', value: '二审' },
  { text: '再审', value: '再审' },
  { text: '执行', value: '执行' }
];

// 新增案件表单
const newCase = ref({
  caseName: '',
  caseProcedure: ''
});

// 修改案件表单
const editCase = ref({
  id: null as number | null,
  caseName: '',
  caseProcedure: ''
});

// 当前选中的案件
const currentCase = ref<CaseListItem | null>(null);

// 操作菜单选项
const actions = computed(() => [
  {
    name: '上传证据材料',
    icon: 'photo',
    disabled: !currentCase.value
  },
  {
    name: '新建案件',
    icon: 'add-o'
  },
  {
    name: '修改案件',
    icon: 'edit',
  }
]);

// 过滤后的案件列表
const filteredCaseList = computed(() => {
  if (!searchValue.value) return caseList.value;
  const search = searchValue.value.toLowerCase();
  return caseList.value.filter(item =>
    item.caseName.toLowerCase().includes(search) ||
    item.caseProcedure.toLowerCase().includes(search)
  );
});

// 案件程序选择确认
const onProcedureConfirm = ({ selectedOptions }: { selectedOptions: { value: string }[] }) => {
  newCase.value.caseProcedure = selectedOptions[0].value;
  showProcedurePicker.value = false;
};

// 修改案件程序选择确认
const onEditProcedureConfirm = ({ selectedOptions }: { selectedOptions: { value: string }[] }) => {
  editCase.value.caseProcedure = selectedOptions[0].value;
  showEditProcedurePicker.value = false;
};

// 搜索案件
const handleSearch = () => {
  ElMessage.success('查询成功');
};


// 查看案件详情（界面跳转）
const viewCaseDetail = (caseItem: CaseListItem) => {
  console.log('查看案件详情:', caseItem);
  // 跳转到AI聊天界面，并传递案件ID
  router.push(`/ai-chat/${caseItem.id}`);
};

// 获取案件列表的方法
const fetchCaseList = async () => {
  try {
    const userNo = localStorage.getItem("userNo") || "defaultUserNo";
    if (!userNo) {
      ElMessage.warning('用户未登录');
      return;
    }

    const response = await getChatHistoriesByUserNo(userNo);
    const realResponse = response.data;

    if (realResponse.code === 200 && realResponse.data && Array.isArray(realResponse.data)) {
      caseList.value = realResponse.data.map((item: any) => ({
        id: item.id,
        caseName: item.caseName || '未命名案件',
        analysisStatus: item.analysisStatus,
        evidenceUpload: item.evidenceUpload,
        caseProcedure: item.caseProcedure,
        victoryRate: item.victoryRate,
        createTime: item.createTime ? item.createTime : new Date().toISOString().split('T')[0]
      }));
    } else {
      ElMessage.warning(realResponse.message || '获取案件列表失败');
    }
  } catch (error) {
    console.error('获取案件列表失败:', error);
    ElMessage.error('获取案件列表失败');
  }
};

// 删除案件
const deleteCase = async (index: number) => {
  try {
    const caseItem = caseList.value[index];
    if (!caseItem) {
      ElMessage.warning('未找到要删除的案件');
      return;
    }
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除这个案件吗？删除后无法恢复',
    });
    console.log('删除案件index:', index);
    console.log('删除案件id:', caseItem.id);
    // 调用后端API删除案件
    const response = await deleteCaseById(caseItem.id);

    if (response.data.code === 200) {
      // 从本地列表中移除
      caseList.value.splice(index, 1);
      ElMessage.success('案件删除成功');
    } else {
      ElMessage.error(response.message || '删除案件失败');
    }
  } catch (error) {
    // 用户点击取消或其他错误
    if (error !== 'cancel') {
      console.error('删除案件失败:', error);
      ElMessage.error('删除案件失败，请稍后重试');
    }
  }
};

// 新增案件
const addNewCase = () => {
  newCase.value = { caseName: '', caseProcedure: '' };
  showAddDialog.value = true;
};

const toGenerateClaimReport = () => {
  router.push('/generateClaimReport');
}

// 确认新增案件
const confirmAddCase = async () => {
  try {
    // 获取当前用户编号
    const userNo = localStorage.getItem('userNo');
    if (!userNo) {
      ElMessage.warning('用户未登录');
      return;
    }
    // 验证表单数据
    if (!newCase.value.caseName || !newCase.value.caseProcedure) {
      ElMessage.warning('请填写完整的案件信息');
      return;
    }

    // 调用后端 API 添加案件
    const response = await addCase({
      userNo,
      caseName: newCase.value.caseName,
      caseProcedure: newCase.value.caseProcedure
    });

    // 处理响应
    if (response.data.code === 200) {
      // 添加成功，刷新案件列表
      await fetchCaseList();
      // 关闭弹窗
      showAddDialog.value = false;
      // 清空表单
      newCase.value = { caseName: '', caseProcedure: '' };
      ElMessage.success('案件添加成功');
    } else {
      ElMessage.error(response.message || '添加案件失败');
    }
  } catch (error) {
    console.error('添加案件出错:', error);
    ElMessage.error('添加案件出错，请稍后重试');
  }
};


/* ============== 案件操作菜单模块 ===================== */
/**
 * 根据不同的选项，进行不同的操作
 */

// 显示操作菜单
const showActionSheet = (caseItem: CaseListItem) => {
  currentCase.value = caseItem;
  showAction.value = true;
};


// 选择操作菜单项
const onSelect = async (action: any) => {
  showAction.value = false;

  try {
    switch (action.name) {
      case '上传证据材料':
        if (!currentCase.value) return;

        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.pdf,.doc,.docx,.jpg,.png';
        input.style.display = 'none';

        input.onchange = async (e: Event) => {
          const target = e.target as HTMLInputElement;
          if (target.files && target.files.length > 0) {
            const loading = ElLoading.service({
              lock: true,
              text: '文件上传中',
              background: 'rgba(0, 0, 0, 0.7)',
            });

            try {
              await uploadCaseFile(currentCase.value!.id, target.files[0]);
              await fetchCaseList();

              const updatedCase = caseList.value.find(item => item.id === currentCase.value?.id);
              if (updatedCase) {
                updatedCase.evidenceUpload = '已完成';
              }
              ElMessage.success('文件上传成功');
            } catch (error) {
              console.error('文件上传失败:', error);
              ElMessage.error('文件上传失败');
            } finally {
              loading.close();
            }
          }
        };

        document.body.appendChild(input);
        input.click();
        document.body.removeChild(input);
        break;

      case '新建案件':
        addNewCase();
        break;

      case '修改案件':
        if (currentCase.value) {
          editCase.value = {
            id: currentCase.value.id,
            caseName: currentCase.value.caseName,
            caseProcedure: currentCase.value.caseProcedure
          };
          console.log(editCase.value);
          showEditDialog.value = true;
        }
        break;
    }
  } catch (error) {
    console.error('操作执行失败:', error);
    ElMessage.error('操作执行失败');
  }
};

// 确认修改案件
const confirmEditCase = async () => {
  try {
    if (!editCase.value.caseName || !editCase.value.caseProcedure) {
      ElMessage.warning('请填写完整的案件信息');
      return;
    }
    if (!editCase.value.id) {
      ElMessage.warning('出错了，请刷新页面后重试');
      return;
    }
    const response = await updateCase({
      id: editCase.value.id,
      caseName: editCase.value.caseName,
      caseProcedure: editCase.value.caseProcedure
    });
    console.log(response);
    if (response.data.code === 200) {
      // 更新案件列表
      await fetchCaseList();
      // 关闭弹窗
      showEditDialog.value = false;
      ElMessage.success('案件修改成功');
    } else {
      ElMessage.error(response.message || '修改案件失败');
    }
  } catch (error) {
    console.error('修改案件出错:', error);
    ElMessage.error('修改案件出错，请稍后重试');
  }
};

onMounted(() => {
  fetchCaseList();
});
</script>

<style scoped>
/* 样式保持不变 */
.case-analysis-dashboard {
  position: relative;
  padding: 0;
  background-color: #f7f8fa;
  min-height: calc(100vh - constant(safe-area-inset-bottom));
  /* iOS 安全区域 */
  min-height: calc(100vh - env(safe-area-inset-bottom));
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  overflow-x: hidden;
}

/* 修复弹窗问题 */
.van-popup {
  border-radius: 16px 16px 0 0;
}

.van-dialog {
  border-radius: 8px;
  overflow: hidden;
}

/* 修复输入框聚焦状态 */
.van-field__control:focus {
  transform: translateZ(0);
  /* 触发硬件加速 */
}

.assistant-header {
  position: relative;
  padding: 20px 16px;
  background: linear-gradient(135deg, #1976D2, #2196F3);
  color: white;
  margin-bottom: 16px;
  border-radius: 0 0 16px 16px;
  overflow: hidden;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: cover;
  opacity: 0.1;
  z-index: 1;
}



.robot-img {
  width: 90px;
  height: 90px;
  margin-right: 16px;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.assistant-info {
  flex: 1;
}

.welcome-title {
  font-size: 22px;
  margin: 0;
  font-weight: 500;
}

.welcome-desc {
  font-size: 14px;
  margin: 8px 0 0;
  opacity: 0.9;
}

.search-area {
  padding: 0 16px;
  margin-bottom: 16px;
}

:deep(.van-search__content) {
  background-color: white;
}

.case-list {
  padding: 0 16px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title h3 {
  font-size: 18px;
  margin: 0;
  color: #333;
}

</style>